package com.maple.common.utils

import android.app.DownloadManager
import android.content.Context
import android.content.Intent
import android.net.Uri
import android.os.Environment
import android.os.StrictMode
import java.io.File

/**
 * Tip:
 * Create by SeVen on 2024/5/13 17:19
 */
class DownloadManagerUtil(context: Context) {

    private var downloadManager: DownloadManager =
        context.getSystemService(Context.DOWNLOAD_SERVICE) as DownloadManager
    private var mContext: Context = context

    companion object {
        fun getInstance(context: Context) =
            DownLoadHelper(context).factory
    }

    class DownLoadHelper(context: Context) {
        val factory = DownloadManagerUtil(context)
    }

    fun downloadApk(apkUrl: String, apkName: String, title: String, desc: String): Long {
        //以下两行代码可以让下载的apk文件被直接安装而不用使用Fileprovider,系统7.0或者以上才启动。
        val localBuilder = StrictMode.VmPolicy.Builder()
        StrictMode.setVmPolicy(localBuilder.build())
        val request = DownloadManager.Request(Uri.parse(apkUrl))
        // 仅允许在WIFI连接情况下下载
        //request.setAllowedNetworkTypes(Request.NETWORK_WIFI)
        // 通知栏中将出现的内容
        request.setTitle(title)
        request.setDescription(desc)
        //7.0以上的系统适配
        request.setRequiresDeviceIdle(false)
        request.setRequiresCharging(false)
        //制定下载的文件类型为APK
        request.setMimeType("application/vnd.android.package-archive");
        // 下载过程和下载完成后通知栏有通知消息。
        request.setNotificationVisibility(
            DownloadManager.Request.VISIBILITY_VISIBLE
                    or DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED
        )
        // 指定下载文件地址，使用这个指定地址可不需要WRITE_EXTERNAL_STORAGE权限。
        request.setDestinationUri(
            Uri.fromFile(
                File(
                    mContext.getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS),
                    apkName
                )
            )
        )
        //表示允许MediaScanner扫描到这个文件，默认不允许。
        request.allowScanningByMediaScanner()
        //启动系统下载界面
        mContext.startActivity(Intent(DownloadManager.ACTION_VIEW_DOWNLOADS))
        return downloadManager.enqueue(request)
    }

    /**
     * 下载前先移除前一个任务，防止重复下载
     * @param downloadId
     */
    fun clearCurrentTask(downloadId: Long) {
        try {
            downloadManager.remove(downloadId)
        } catch (ex: IllegalArgumentException) {
            ex.printStackTrace()
        }
    }
}